<template>
  <div class="blog-list">
    <div class="blog-items">
      <div class="section-header">
        <div class="section-title">
          <h3>博客列表</h3>
          <div class="post-filters">
            <button 
              v-for="filter in filters" 
              :key="filter.id"
              :class="{ active: filter.id === articleStore.currentCategory }"
              @click="articleStore.setCategory(filter.id)"
            >
              {{ filter.name }}
            </button>
          </div>
        </div>
        <button v-if="userStore.isLogin" class="add-post-btn" @click="showAddPostForm = true">
          <i class="fas fa-plus"></i>
          写博客
        </button>
      </div>

      <!-- 添加文章表单 -->
      <div v-if="showAddPostForm" class="add-post-form">
        <div class="form-header">
          <h3>发布新文章</h3>
          <button class="close-btn" @click="showAddPostForm = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="form-content">
          <div class="form-group">
            <label>标题</label>
            <input 
              v-model="newPost.title" 
              type="text" 
              placeholder="请输入文章标题"
            >
          </div>
          <div class="form-group">
            <label>摘要</label>
            <textarea 
              v-model="newPost.summary" 
              placeholder="请输入文章摘要"
              rows="3"
            ></textarea>
          </div>
          <div class="form-group">
            <label>正文内容</label>
            <textarea 
              v-model="newPost.content" 
              placeholder="支持 Markdown 格式"
              rows="10"
            ></textarea>
          </div>
          <div class="form-group">
            <label>分类</label>
            <select v-model="newPost.category">
              <option value="tech">技术</option>
              <option value="career">职场</option>
              <option value="life">生活</option>
            </select>
          </div>
          <div class="form-actions">
            <button class="cancel-btn" @click="showAddPostForm = false">取消</button>
            <button class="submit-btn" @click="addNewPost">发布</button>
          </div>
        </div>
      </div>

      <div v-if="loading" class="loading-state">
        <i class="fas fa-spinner fa-spin"></i>
        加载中...
      </div>
      
      <div v-else-if="filteredBlogs.length === 0" class="empty-state">
        暂无文章
      </div>
      
      <template v-else>
        <BlogItem 
          v-for="blog in filteredBlogs" 
          :key="blog.id" 
          :blog="blog"
        />
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import BlogItem from './BlogItem.vue'
import { useArticleStore } from '../stores/articleStore'
import { useUserStore } from '../stores/userStore'

const router = useRouter()
const articleStore = useArticleStore()
const userStore = useUserStore()

const filters = [
  { id: 'all', name: '全部' },
  { id: 'tech', name: '技术' },
  { id: 'career', name: '职场' },
  { id: 'life', name: '生活' }
]

const loading = ref(false)
const showAddPostForm = ref(false)

const newPost = ref({
  title: '',
  summary: '',
  category: 'tech',
  content: ''
})

const formatBlogData = (article) => {
  return {
    id: article.id,
    title: article.title,
    summary: article.summary,
    createTime: new Date(article.create_time).toLocaleString(),
    author: {
      name: article.author_name,
      avatar: article.author_avatar
    },
    authorId: article.user_id,
    stats: {
      comments: article.comment_count || 0,
      likes: article.like_count || 0,
      shares: article.share_count || 0,
      views: article.view_count || 0
    }
  }
}

const filteredBlogs = computed(() => {
  return articleStore.getArticlesByCategory.map(formatBlogData)
})

onMounted(async () => {
  try {
    loading.value = true
    await articleStore.fetchArticles()
  } catch (error) {
    console.error('获取文章列表失败:', error)
  } finally {
    loading.value = false
  }
})

const addNewPost = async () => {
  if (!newPost.value.title || !newPost.value.summary || !newPost.value.content) {
    alert('请填写完整的文章信息')
    return
  }

  try {
    const articleData = {
      title: newPost.value.title,
      summary: newPost.value.summary,
      content: newPost.value.content,
      category: newPost.value.category,
      user_id: userStore.currentUser.id
    }

    console.log('发送的文章数据:', articleData)

    const newArticle = await articleStore.createArticle(articleData)

    // 重置表单
    newPost.value = {
      title: '',
      summary: '',
      category: 'tech',
      content: ''
    }

    showAddPostForm.value = false
    
    // 刷新文章列表
    await articleStore.fetchArticles()

    // 跳转到新文章页面
    router.push({
      name: 'article',
      params: { id: newArticle.id }
    })
  } catch (error) {
    alert('发布文章失败：' + error.message)
  }
}
</script>
<style scoped>
.blog-list {
  max-width: 100%;
}

.blog-items {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 24px;
}

.section-title h3 {
  font-size: 20px;
  color: var(--text-color);
  margin: 0;
}

.post-filters {
  display: flex;
  gap: 12px;
}

.post-filters button {
  background: none;
  border: none;
  color: var(--text-light);
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.post-filters button.active {
  background: var(--primary-color);
  color: white;
}

.add-post-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.add-post-btn:hover {
  background: #0052a3;
}

.add-post-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 24px;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-lighter);
  cursor: pointer;
  padding: 4px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: var(--text-color);
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.cancel-btn {
  background: none;
  border: 1px solid var(--border-color);
  color: var(--text-light);
}

.submit-btn {
  background: var(--primary-color);
  border: none;
  color: white;
}

.loading-state,
.empty-state {
  text-align: center;
  padding: 40px;
  color: var(--text-light);
}

.loading-state i {
  margin-right: 8px;
}
</style>

